package zhang.lao.api.service.app;/**
 * Created by zhangqin on 2018/1/12.
 */

import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.plugin.util.UIUtil;
import zhang.lao.build.mybatis.generator.util.StringUtil;
import zhang.lao.build.mybatis.jdbc.auto.model.*;
import zhang.lao.build.tool.*;
import zhang.lao.build.tool.date.DateStyle;
import zhang.lao.build.tool.date.DateUtil;
import zhang.lao.dao.base.*;
import zhang.lao.pojo.api.req.ApiReqData;
import zhang.lao.pojo.api.req.app.*;
import zhang.lao.pojo.api.resp.ApiRespData;
import zhang.lao.pojo.api.resp.ApiResultEnum;
import zhang.lao.pojo.api.resp.app.*;
import zhang.lao.service.sms.SmsService;
import zhang.lao.service.sms.SmsServiceImp;

import javax.annotation.Resource;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author
 * @create 2018-01-12 10:35
 **/
@Service
public class AppService {
    @Autowired
    private WnAppUserWorkAuthDao wnAppUserWorkAuthDao;
    @Autowired
    private WnLnglatAppDao wnLnglatAppDao;
    @Autowired
    private WnLnglatAppNewDao wnLnglatAppNewDao;
    @Autowired
    private WnMachineDao wnMachineDao;
    @Autowired
    private WnMachineToolDao wnMachineToolDao;
    @Autowired
    private WnMachineToolLinkDao wnMachineToolLinkDao;
    @Resource
    private SmsService smsService;;
    @Autowired
    private WnAppUserWorkDao wnAppUserWorkDao;
    @Autowired
    private WnAppUserDao wnAppUserDao;

    /**
     * 上传轨迹信息
     * @param apiReqData
     * @return
     */
    @Transactional
    public ApiRespData uplatlng(ApiReqData<ApiUplatlngReq> apiReqData){
        ApiUplatlngReq body = apiReqData.getBody();
        WnLnglatApp wnLnglatApp = new WnLnglatApp();
        wnLnglatApp.setAccuracy(body.getAccuracy());
        wnLnglatApp.setAppUserId(body.getUserId());
        wnLnglatApp.setCreateTime(new Date(Long.parseLong(body.getTimestamp())));
        wnLnglatApp.setHeight(Double.parseDouble(body.getAltitude()));
        wnLnglatApp.setLat(body.getLatitude());
        wnLnglatApp.setLng(body.getLongitude());
        wnLnglatApp.setLocationType(body.getLocationType());
        DecimalFormat df = new DecimalFormat("#");
        String format = df.format(Double.parseDouble(body.getHeading()));
        wnLnglatApp.setOrentation(Integer.parseInt(format));
        wnLnglatApp.setState(1);
        wnLnglatApp.setSpeed(Double.valueOf(body.getSpeed()));
        wnLnglatAppDao.insertSelective(wnLnglatApp);

        WnLnglatAppNewExample wnLnglatAppNewExample = new WnLnglatAppNewExample();
        wnLnglatAppNewExample.createCriteria().andAppUserIdEqualTo(wnLnglatApp.getAppUserId());
        WnLnglatAppNew first = ListUtils.getFirst(wnLnglatAppNewDao.selectByExample(wnLnglatAppNewExample));
        if(first!=null){
            Integer id = first.getId();
            BeanUtils.copyProperties(wnLnglatApp,first);
            first.setId(id);
            wnLnglatAppNewDao.updateByPrimaryKey(first);
        }else{
            WnLnglatAppNew wnLnglatAppNew = new WnLnglatAppNew();
            BeanUtils.copyProperties(wnLnglatApp,wnLnglatAppNew);
            wnLnglatAppNewDao.insert(wnLnglatAppNew);
        }
        return ApiRespData.buildSucc();
    }

    /**
     * 获取验证码
     * @param apiPhoneCodeReqApiReqData
     * @return
     */
    public ApiRespData getPhoneCode(ApiReqData<ApiPhoneCodeReq> apiPhoneCodeReqApiReqData ){
        String phoneNumber = apiPhoneCodeReqApiReqData.getBody().getPhoneNumber();
        String validateCode = smsService.getValidateCode(phoneNumber);
        ApiPhoneCodeResp apiPhoneCodeResp = new ApiPhoneCodeResp();
        apiPhoneCodeResp.setPhoneCode(validateCode);
        return ApiRespData.buildSucc(apiPhoneCodeResp);
    }

    /**
     * 登录
     * @param apiPhoneCodeReqApiReqData
     * @return
     */
    public ApiRespData login(ApiReqData<ApiLoginReq> apiPhoneCodeReqApiReqData ){
        String phoneNumber = apiPhoneCodeReqApiReqData.getBody().getPhoneNumber();
        String validateCode = apiPhoneCodeReqApiReqData.getBody().getPhoneCode();
        boolean b = smsService.validateCode(phoneNumber, validateCode);
        if(b){
            WnAppUserExample wnAppUserExample = new WnAppUserExample();
            wnAppUserExample.createCriteria().andPhoneNumberEqualTo(phoneNumber);
            int i = wnAppUserDao.countByExample(wnAppUserExample);
            if(i<1){
                WnAppUser wnAppUser = new WnAppUser();
                wnAppUser.setId(UUIDTool.getUUID());
                wnAppUser.setCreateTime(new Date());
                wnAppUser.setPhoneNumber(phoneNumber);
                wnAppUserDao.insertSelective(wnAppUser);
                return  ApiRespData.buildSucc(new ApiLoginResp(false,wnAppUser.getId(),wnAppUser.getNickName()));
            }else{
                List<WnAppUser> wnAppUsers = wnAppUserDao.selectByExample(wnAppUserExample);
                WnAppUser first = ListUtils.getFirst(wnAppUsers);
                return  ApiRespData.buildSucc(new ApiLoginResp(true,first.getId(),first.getNickName()));
            }
        }else{
            return ApiRespData.buildFail(ApiResultEnum.PHONECODEERROR);
        }
    }



       /**
     * 获取农机信息
     * @return
     */
    public ApiRespData<ApiMachineInfoResp> getMachineInfo(ApiReqData<ApiMachineInfoReq> apiReqData ){
        String machineNumber = apiReqData.getBody().getMachineNumber();
        WnMachineExample wnMachineExample = new WnMachineExample();
        wnMachineExample.createCriteria().andMachineNumberEqualTo(machineNumber);
        WnMachine first = ListUtils.getFirst(wnMachineDao.selectByExample(wnMachineExample));
        if(first==null){
            return ApiRespData.buildFail(ApiResultEnum.NOFINDMACHINE);
        }else{
            ApiMachineInfoResp apiMachineInfoResp = new ApiMachineInfoResp();
            apiMachineInfoResp.setMachineId(first.getId());
            apiMachineInfoResp.setMachineNumber(first.getMachineNumber());
            apiMachineInfoResp.setMachineCarNumber(first.getLicensePlateNumber());
            WnMachineToolLinkExample wnMachineToolLinkExample = new WnMachineToolLinkExample();
            wnMachineToolLinkExample.createCriteria().andMachineIdEqualTo(first.getId());
            WnMachineToolLink first1 = ListUtils.getFirst(wnMachineToolLinkDao.selectByExample(wnMachineToolLinkExample));
            if(first1!=null){
                WnMachineTool wnMachineTool = wnMachineToolDao.selectByPrimaryKey(first1.getMachineToolId());
                apiMachineInfoResp.setMachineToolNumber(wnMachineTool.getToolNumber());
            }else{
                apiMachineInfoResp.setMachineToolNumber("0");
            }
            return ApiRespData.buildSucc(apiMachineInfoResp);
        }

    }


    /**
     * 获取农机机具信息
     * @return
     */
    public ApiRespData<ApiMachineToolResp> getMachineToolInfo(ApiReqData<ApiMachineToolInfoReq> apiReqData ){
        String machineToolNumber = apiReqData.getBody().getMachineToolNumber();
        WnMachineToolExample wnMachineToolExample = new WnMachineToolExample();
        wnMachineToolExample.createCriteria().andToolNumberEqualTo(machineToolNumber);
        WnMachineTool first = ListUtils.getFirst(wnMachineToolDao.selectByExample(wnMachineToolExample));
        if(first==null){
            return ApiRespData.buildFail(ApiResultEnum.NOFINDMACHINETOOL);
        }else{
            ApiMachineToolResp apiMachineToolResp = new ApiMachineToolResp();
            apiMachineToolResp.setMachineToolNumber(first.getToolNumber());
            apiMachineToolResp.setMachineToolType(first.getType());
            apiMachineToolResp.setMachineToolWidth(first.getBreadth()+"");
            apiMachineToolResp.setMachineToolId(first.getId());
            return ApiRespData.buildSucc(apiMachineToolResp);
        }

    }


    /**
     * 开始工作
     * @return
     */
    public ApiRespData<ApiStartWorkResp> startWork(ApiReqData<ApiWorkStartReq> apiReqData ){

        ApiWorkStartReq apiWorkStartReq = apiReqData.getBody();
        WnAppUserWorkExample wnAppUserWorkExample = new WnAppUserWorkExample();
        wnAppUserWorkExample.createCriteria().andAppUserIdEqualTo(apiWorkStartReq.getAppUserId()).andFinishStateEqualTo(0).andDelStateEqualTo(0);
        WnAppUserWork first = ListUtils.getFirst(wnAppUserWorkDao.selectByExample(wnAppUserWorkExample));
        if(first!=null){
            return ApiRespData.buildFail(ApiResultEnum.WORKNOSTOP);
        }
        WnAppUserWork wnAppUserWork = new WnAppUserWork();
        BeanUtils.copyProperties(apiWorkStartReq,wnAppUserWork);
        wnAppUserWork.setStartTime(new Date());
        wnAppUserWork.setDelState(0);
        wnAppUserWork.setId(UUIDTool.getUUID());
        wnAppUserWork.setFinishState(0);
        wnAppUserWorkDao.insertSelective(wnAppUserWork);
        ApiStartWorkResp apiStartWorkResp = new ApiStartWorkResp();
        apiStartWorkResp.setWorkId(wnAppUserWork.getId());
        return ApiRespData.buildSucc(apiStartWorkResp);
    }

    /**
     * 结束工作
     * @return
     */
    @Transactional
    public ApiRespData endWork(ApiReqData<ApiWorkEndReq> apiReqData ){

        String workId = apiReqData.getBody().getWorkId();
        if(StringUtils.isBlank(workId)){
            workId = runningWork(apiReqData).getBody().getWorkId();
        }
        WnAppUserWork wnAppUserWork = wnAppUserWorkDao.selectByPrimaryKey(workId);
        if(!wnAppUserWork.getAppUserId().equals(apiReqData.getUid())){
            return ApiRespData.buildFail(ApiResultEnum.NOAUTHDATA);
        }

        wnAppUserWork.setEndTime(new Date());
        wnAppUserWork.setFinishState(1);
       WnAppUserWorkAuth wnAppUserWorkAuth = new WnAppUserWorkAuth();
       wnAppUserWorkAuth.setAuthState(0);
       wnAppUserWorkAuth.setId(UUIDTool.getUUID());
       wnAppUserWorkAuth.setWorkId(wnAppUserWork.getId());
        DecimalFormat df = new DecimalFormat("#.00");
        String format = df.format(getArea(wnAppUserWork.getAppUserId(), wnAppUserWork.getStartTime(), wnAppUserWork.getEndTime(), wnAppUserWork.getWorkWidth()));
        wnAppUserWorkAuth.setWorkArea(Float.parseFloat(format));
        long l = wnAppUserWork.getEndTime().getTime() - wnAppUserWork.getStartTime().getTime();
        wnAppUserWorkAuth.setWorkDurationTime(Integer.parseInt(Long.toString(l/60000)));
        wnAppUserWorkDao.updateByPrimaryKey(wnAppUserWork);
        wnAppUserWorkAuthDao.insertSelective(wnAppUserWorkAuth);
        return ApiRespData.buildSucc();
    }

    /**
     * 计算面积
     * @param appUserId
     * @param startTime
     * @param endTime
     * @param width
     * @return
     */
    private double getArea(String appUserId,Date startTime,Date endTime,double width){
        WnLnglatAppExample wnLnglatAppExample = new WnLnglatAppExample();
        wnLnglatAppExample.createCriteria().andAppUserIdEqualTo(appUserId).andCreateTimeGreaterThan(startTime).andCreateTimeLessThan(endTime).andLocationTypeEqualTo(1);;
        List<WnLnglatApp> wnLnglatApps = wnLnglatAppDao.selectByExample(wnLnglatAppExample);
        double distance = 0.00;
        double area = 0.00;
        if(ListUtils.isNotEmpty(wnLnglatApps)){
            for (int i = 1; i < wnLnglatApps.size(); i++) {
                WnLnglatApp wnLnglatAppStart = wnLnglatApps.get(i-1);
                WnLnglatApp wnLnglatAppEnd = wnLnglatApps.get(i);
                double getdistance = MapTool.getdistance(wnLnglatAppStart.getLat(), wnLnglatAppStart.getLng(), wnLnglatAppEnd.getLat(), wnLnglatAppEnd.getLng());
                distance+=getdistance;
            }
        }
        if(distance>0){
            area = distance * width * 1000 * 0.0015;
        }
        return area;
    }
    /**
     * 删除工作
     * @return
     */
    public ApiRespData delWork(ApiReqData<ApiWorkDelReq> apiReqData ){
        String workId = apiReqData.getBody().getWorkId();
        if(StringUtils.isBlank(workId)){
            workId = runningWork(apiReqData).getBody().getWorkId();
        }
        WnAppUserWork wnAppUserWork = wnAppUserWorkDao.selectByPrimaryKey(workId);
        if(!wnAppUserWork.getAppUserId().equals(apiReqData.getUid())){
            return ApiRespData.buildFail(ApiResultEnum.NOAUTHDATA);
        }
        wnAppUserWork.setEndTime(new Date());
        wnAppUserWork.setFinishState(1);
        wnAppUserWork.setDelState(1);
        wnAppUserWorkDao.updateByPrimaryKey(wnAppUserWork);
        return ApiRespData.buildSucc();
    }

    /**
     * 工作详情
     * @return
     */
    public ApiRespData<ApiWorkInfoResp> infoWork(ApiReqData<ApiWorkInfoReq> apiReqData ){


        WnAppUserWork wnAppUserWork = wnAppUserWorkDao.selectByPrimaryKey(apiReqData.getBody().getWorkId());
        if(!wnAppUserWork.getAppUserId().equals(apiReqData.getUid())){
            return ApiRespData.buildFail(ApiResultEnum.NOAUTHDATA);
        }
        ApiWorkInfoResp apiWorkInfoResp = new ApiWorkInfoResp();
        BeanUtils.copyProperties(wnAppUserWork,apiWorkInfoResp);
        apiWorkInfoResp.setWorkId(wnAppUserWork.getId());
        WnMachine wnMachine = wnMachineDao.selectByPrimaryKey(wnAppUserWork.getMachineId());
        apiWorkInfoResp.setMachineCarNumber(wnMachine.getLicensePlateNumber());
        WnAppUserWorkAuthExample wnAppUserWorkAuthExample = new WnAppUserWorkAuthExample();
        wnAppUserWorkAuthExample.createCriteria().andWorkIdEqualTo(wnAppUserWork.getId());
        WnAppUserWorkAuth first = ListUtils.getFirst(wnAppUserWorkAuthDao.selectByExample(wnAppUserWorkAuthExample));
        if(first!=null){
            apiWorkInfoResp.setWorkArea(first.getWorkArea()+"亩");
            apiWorkInfoResp.setWorkAuth(first.getAuthState()==1?"审核通过":"已审核");
            apiWorkInfoResp.setWorkTime(first.getWorkDurationTime()+"分钟");
        }

        return ApiRespData.buildSucc(apiWorkInfoResp);
    }
    /**
     * 工作列表
     * @return
     */
    public ApiRespData<List<ApiWorkInfoResp>> workList(ApiReqData<ApiWorkListReq> apiReqData ){
        List<ApiWorkInfoResp> apiWorkInfoRespList = Lists.newArrayList();
        String date = apiReqData.getBody().getDate();
        WnAppUserWorkExample wnAppUserWorkExample = new WnAppUserWorkExample();
        wnAppUserWorkExample.createCriteria().andAppUserIdEqualTo(apiReqData.getUid()).andStartTimeLessThan(DateUtil.StringToDate(date+" 23:59:59")).andStartTimeGreaterThan(DateUtil.StringToDate(date+" 00:00:00"));
        wnAppUserWorkExample.setOrderByClause("start_time desc");
        List<WnAppUserWork> wnAppUserWorks = wnAppUserWorkDao.selectByExample(wnAppUserWorkExample);
        if(ListUtils.isEmpty(wnAppUserWorks)){
            return ApiRespData.buildFail(ApiResultEnum.NOWORKLIST);
        }else {
            for (WnAppUserWork wnAppUserWork : wnAppUserWorks) {
                ApiWorkInfoResp apiWorkInfoResp = new ApiWorkInfoResp();
                BeanUtils.copyProperties(wnAppUserWork, apiWorkInfoResp);
                apiWorkInfoResp.setStartTime(DateUtil.DateToString(wnAppUserWork.getStartTime(), DateStyle.YYYY_MM_DD_HH_MM));
                apiWorkInfoResp.setEndTime(DateUtil.DateToString(wnAppUserWork.getEndTime(), DateStyle.YYYY_MM_DD_HH_MM));
                apiWorkInfoResp.setWorkId(wnAppUserWork.getId());
                WnMachine wnMachine = wnMachineDao.selectByPrimaryKey(wnAppUserWork.getMachineId());
                apiWorkInfoResp.setMachineCarNumber(wnMachine.getLicensePlateNumber());
                WnAppUserWorkAuthExample wnAppUserWorkAuthExample = new WnAppUserWorkAuthExample();
                wnAppUserWorkAuthExample.createCriteria().andWorkIdEqualTo(wnAppUserWork.getId());
                WnAppUserWorkAuth first = ListUtils.getFirst(wnAppUserWorkAuthDao.selectByExample(wnAppUserWorkAuthExample));
                if (first != null) {
                    apiWorkInfoResp.setWorkArea(first.getWorkArea() + "亩");
                    apiWorkInfoResp.setWorkAuth(first.getAuthState() == 1 ? "审核通过" : "已审核");
                    apiWorkInfoResp.setWorkTime(first.getWorkDurationTime() + "分钟");
                }
                apiWorkInfoRespList.add(apiWorkInfoResp);
            }
            return ApiRespData.buildSucc(apiWorkInfoRespList);
        }

    }


    /**
     * 获取正在进行的工作
     * @return
     */
    public ApiRespData<ApiWorkInfoResp> runningWork(ApiReqData apiReqData ){
        WnAppUserWorkExample wnAppUserWorkExample = new WnAppUserWorkExample();
        wnAppUserWorkExample.createCriteria().andAppUserIdEqualTo(apiReqData.getUid()).andFinishStateEqualTo(0).andDelStateEqualTo(0);
        WnAppUserWork first = ListUtils.getFirst(wnAppUserWorkDao.selectByExample(wnAppUserWorkExample));
        if(first!=null){
            ApiWorkInfoResp apiWorkInfoResp = new ApiWorkInfoResp();
            BeanUtils.copyProperties(first,apiWorkInfoResp);
            apiWorkInfoResp.setStartTime(DateUtil.DateToString(first.getStartTime(), DateStyle.YYYY_MM_DD_HH_MM));
            apiWorkInfoResp.setEndTime(DateUtil.DateToString(first.getEndTime(), DateStyle.YYYY_MM_DD_HH_MM));
            apiWorkInfoResp.setWorkId(first.getId());
            WnMachine wnMachine = wnMachineDao.selectByPrimaryKey(first.getMachineId());
            apiWorkInfoResp.setMachineCarNumber(wnMachine.getLicensePlateNumber());
            WnLnglatAppNewExample wnLnglatAppNewExample = new WnLnglatAppNewExample();
            wnLnglatAppNewExample.createCriteria().andAppUserIdEqualTo(apiReqData.getUid()).andCreateTimeGreaterThan(first.getStartTime());
            WnLnglatAppNew first1 = ListUtils.getFirst(wnLnglatAppNewDao.selectByExample(wnLnglatAppNewExample));
            if(first1!=null){
                Point point = CoordinateConversion.wgs_gcj_encrypts(Double.parseDouble(first1.getLat()), Double.parseDouble(first1.getLng()));
                apiWorkInfoResp.setLat(point.getLat()+"");
                apiWorkInfoResp.setLng(point.getLng()+"");
                apiWorkInfoResp.setSpeed(first1.getSpeed()+"");
                apiWorkInfoResp.setOrentation(first1.getOrentation()+"");
            }
            return ApiRespData.buildSucc(apiWorkInfoResp);
        }else{
            return ApiRespData.buildFail(ApiResultEnum.WORKNORUNNING);
        }

    }


    /**
     * 工作轨迹
     * @return
     */
    public ApiRespData workTrace(ApiReqData<ApiWorkInfoReq> apiReqData ){
        String workId = apiReqData.getBody().getWorkId();
        if(StringUtils.isBlank(workId)){
            workId = runningWork(apiReqData).getBody().getWorkId();
        }
        WnAppUserWork wnAppUserWork = wnAppUserWorkDao.selectByPrimaryKey(workId);
        String appUserId = wnAppUserWork.getAppUserId();
        Date startTime = wnAppUserWork.getStartTime();
        Date endTime = wnAppUserWork.getEndTime();
        WnLnglatAppExample wnLnglatAppExample = new WnLnglatAppExample();
        WnLnglatAppExample.Criteria criteria = wnLnglatAppExample.createCriteria();
        criteria.andAppUserIdEqualTo(appUserId).andCreateTimeGreaterThan(startTime);
        if(endTime!=null){
            criteria.andCreateTimeLessThan(endTime);
        }
        wnLnglatAppExample.createCriteria().andLocationTypeEqualTo(1);
        wnLnglatAppExample.setOrderByClause("create_time asc");
        List<WnLnglatAppResp> lnglatAppResps = Lists.newArrayList();
        List<WnLnglatApp> wnLnglatApps = wnLnglatAppDao.selectByExample(wnLnglatAppExample);
        if(ListUtils.isNotEmpty(wnLnglatApps)){
            for (WnLnglatApp wnLnglatApp : wnLnglatApps) {
                WnLnglatAppResp wnLnglatAppResp = new WnLnglatAppResp();
                BeanUtils.copyProperties(wnLnglatApp,wnLnglatAppResp);
                wnLnglatAppResp.setCreateTime(DateUtil.DateToString(wnLnglatApp.getCreateTime(),DateStyle.YYYY_MM_DD_HH_MM_SS));
                Point  point = CoordinateConversion.wgs_gcj_encrypts(Double.parseDouble(wnLnglatApp.getLat()), Double.parseDouble(wnLnglatApp.getLng()));
                 wnLnglatAppResp.setLat(point.getLat()+"");
                wnLnglatAppResp.setLng(point.getLng()+"");
                lnglatAppResps.add(wnLnglatAppResp);
            }
        }else{
            return ApiRespData.buildFail(ApiResultEnum.NOWORKTrace);
        }
        return ApiRespData.buildSucc(lnglatAppResps);
    }

    public ApiRespData upDateUserInfo(ApiReqData<ApiUpdateUserInfo> apiUpdateUserInfoApiReqData){
        WnAppUser wnAppUser = wnAppUserDao.selectByPrimaryKey(apiUpdateUserInfoApiReqData.getUid());
        if(wnAppUser!=null){
            wnAppUser.setNickName(apiUpdateUserInfoApiReqData.getBody().getNickName());
            wnAppUserDao.updateByPrimaryKey(wnAppUser);
        }
        return ApiRespData.buildSucc();
    }

    public static void main(String[] args) {
        DecimalFormat df = new DecimalFormat("#");
        String format = df.format(258.6);
        System.out.println(format);
    }
}
